import React, {useEffect, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {Button, DatePicker, Form, Input, message, Select, Tag} from 'antd';
import ProTable from '@ant-design/pro-table';
import HttpRequest from "@/utils/HttpRequest";
import {defaultDomain} from "@/config/domain";
import moment from 'moment'
import ReactJson from 'react-json-view'
import onCopy, {FormatDateTime} from "@/utils/DateTime";
import {MessageDetail} from "@/pages/message/MessageDetail";

const { RangePicker } = DatePicker

const Message: React.FC = () => {
  const [hideMe, setHideMe] = useState('')
  const [msgHide, setMsgHide] = useState('none')
  const [msgLabel, setMsgLabel] = useState('Message Key')
  const [groupList, setGroupList] = useState([])
  const [keyRequire, setKeyRequire] = useState(false)
  const [timeRequire, setTimeRequire] = useState(true)
  const [dataSource, setDataSource] = useState([])
  const [selectedTopics, setSelectedTopics] = useState('')
  const [loading, setLoading] = useState(false)
  // @ts-ignore
  const [defaultValue, setDefaultValue] = useState(['1'])

  const searchByTopic = 1
  const searchByMsgId = 2
  const searchByKey = 3

  // @ts-ignore
  useEffect(async () => {
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: '/topic/list.query',
      method: 'GET',
      params: {},
    })
    console.log('res=', res)
    // @ts-ignore
    const data = res.data
    const itemList = data?.topicList
    // @ts-ignore
    const dList = []
    if (itemList) {
      for (const i in itemList) {
        let d = itemList[i]
        if (!d.startsWith('%')) {
          dList.push(itemList[i])
        }
      }
    }
    // @ts-ignore
    setGroupList(dList)
  }, [])

  function doSelect(v: any) {
    console.log('vvv=', v)
    if (v == searchByTopic) {
      setHideMe('')
      setMsgHide('none')
      setTimeRequire(true)
      setKeyRequire(false)
    } else {
      setMsgHide('')
      setHideMe('none')
      setTimeRequire(false)
      setKeyRequire(true)
      if (v == searchByKey) {
        setMsgLabel('Message Key')
      } else if (v == searchByMsgId) {
        setMsgLabel('Message ID')
      }
    }
  }

  function bindProp(record: {
    isJson: boolean
    messageBody: any
    properties: any
    proList: any
  }) {
    let p = record.properties
    const dataList = []
    if (p) {
      for (const i in p) {
        console.log(i, p[i])
        dataList.push({ key: i, value: p[i] })
      }
    }

    try {
      record.messageBody = JSON.parse(record.messageBody)
      record.isJson = true
    } catch (e) {
      record.isJson = false
      record.messageBody = { '>': JSON.stringify(record.messageBody) }
      record.proList = dataList
    }
  }

  function getSearchTopicValue(v: any) {
    setSelectedTopics(v)
  }

  async function doSearch(v: any) {
    let searchType = v.searchType
    let topic = v.topic
    let messageKey = v.messageKey
    let timeRange = v.timeRange
    let url = ''
    if (searchType == searchByKey) {
      url =
        '/message/queryMessageByTopicAndKey.query?key=' +
        messageKey +
        '&topic=' +
        topic
    } else if (searchType == searchByMsgId) {
      url = '/message/viewMessage.query?msgId=' + messageKey + '&topic=' + topic
    } else if (searchType == searchByTopic) {
      let begin = timeRange[0].valueOf()
      let end = timeRange[1].valueOf()
      url =
        '/message/queryMessageByTopic.query?begin=' +
        begin +
        '&end=' +
        end +
        '&topic=' +
        topic
    }

    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })
    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    let dataList = []
    if (status === 0) {
      if (searchType == searchByMsgId || searchType == searchByKey) {
        const messageView = res.data.messageView
        if (messageView) {
          messageView.strProp = JSON.stringify(messageView.properties)
          bindProp(messageView)
          dataList.push(messageView)
        }
      } else {
        const resData = res.data
        if (resData) {
          for (const i in resData) {
            const messageView = resData[i]
            messageView.strProp = JSON.stringify(messageView.properties)
            dataList.push(messageView)
          }
        }
      }
      // @ts-ignore
      setDataSource(dataList)
      console.log('>>>', dataList)
      if (dataList && dataList.length <= 0) {
        message.info('暂时没有数据')
      }
    } else {
      message.error('查询不到数据')
      setDataSource([])
    }
  }

  async function getMessage(messageKey: string, record: any) {
    setLoading(true)
    // @ts-ignore
    let url =
      '/message/viewMessage.query?msgId=' +
      messageKey +
      '&topic=' +
      selectedTopics
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      const resData = res.data
      if (resData) {
        const messageView = resData.messageView
        console.log('messageView', messageView)
        try {
          record.messageBody = JSON.parse(messageView.messageBody)
          record.isJson = true
        } catch (e) {
          record.isJson = false
          record.messageBody = { '>': JSON.stringify(messageView.messageBody) }
        }
      }
    }

    setLoading(false)
  }

  return (
    <PageContainer>
      <Form
        name="wrap"
        labelCol={{ flex: '110px' }}
        labelAlign="left"
        wrapperCol={{ flex: 1 }}
        colon={false}
        onFinish={doSearch}
      >
        <Input.Group compact>
          <Form.Item
            label="查询方式："
            name="searchType"
            initialValue={['1']}
            rules={[{ required: true }]}
            style={{ display: 'inline-block', width: 'calc(20% - 8px)' }}
          >
            <Select onChange={doSelect}>
              <Select.Option value="1">按照Topic查询</Select.Option>
              <Select.Option value="2">按照Message Id查询</Select.Option>
              <Select.Option value="3">按照Message Key查询</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="Topic"
            name="topic"
            rules={[{ required: true }]}
            style={{
              display: 'inline-block',
              width: 'calc(30% - 8px)',
              marginLeft: '10px',
            }}
          >
            <Select
              showSearch={true}
              onSelect={getSearchTopicValue}
              allowClear={true}
            >
              {groupList.map((item) => (
                <Select.Option value={item} key={item}>
                  {item}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label={msgLabel}
            name="messageKey"
            rules={[{ required: keyRequire }]}
            style={{
              display: msgHide,
              width: 'calc(35% - 8px)',
              marginLeft: '10px',
            }}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="时间范围"
            name="timeRange"
            rules={[{ required: timeRequire }]}
            style={{
              display: hideMe,
              width: 'calc(30% - 8px)',
              marginLeft: '10px',
            }}
          >
            <RangePicker
              ranges={{
                //startDate: moment().startOf('day').subtract(6, 'days')
                '1分钟': [
                  moment().startOf('minute').subtract(1, 'minutes'),
                  moment(),
                ],
                '2分钟': [
                  moment().startOf('minute').subtract(2, 'minutes'),
                  moment(),
                ],
                '3分钟': [
                  moment().startOf('minute').subtract(3, 'minutes'),
                  moment(),
                ],
                '5分钟': [
                  moment().startOf('minute').subtract(5, 'minutes'),
                  moment(),
                ],
                '10分钟': [
                  moment().startOf('minute').subtract(10, 'minutes'),
                  moment(),
                ],
                '15分钟': [
                  moment().startOf('minute').subtract(15, 'minutes'),
                  moment(),
                ],
                '30分钟': [
                  moment().startOf('minute').subtract(30, 'minutes'),
                  moment(),
                ],
                '1小时': [
                  moment().startOf('minute').subtract(60, 'minutes'),
                  moment(),
                ],
                '2小时': [
                  moment().startOf('minute').subtract(120, 'minutes'),
                  moment(),
                ],
                '3小时': [
                  moment().startOf('minute').subtract(180, 'minutes'),
                  moment(),
                ],
                '5小时': [
                  moment().startOf('minute').subtract(300, 'minutes'),
                  moment(),
                ],
                '8小时': [
                  moment().startOf('minute').subtract(480, 'minutes'),
                  moment(),
                ],
                '10小时': [
                  moment().startOf('minute').subtract(600, 'minutes'),
                  moment(),
                ],
                '12小时': [
                  moment().startOf('minute').subtract(720, 'minutes'),
                  moment(),
                ],
                '1天': [moment().startOf('day').subtract(1, 'days'), moment()],
                '2天': [moment().startOf('day').subtract(2, 'days'), moment()],
                '3天': [moment().startOf('day').subtract(3, 'days'), moment()],
                '5天': [moment().startOf('day').subtract(5, 'days'), moment()],
                '7天': [moment().startOf('day').subtract(7, 'days'), moment()],
                '10天': [
                  moment().startOf('day').subtract(10, 'days'),
                  moment(),
                ],
                '15天': [
                  moment().startOf('day').subtract(15, 'days'),
                  moment(),
                ],
                '30天': [
                  moment().startOf('day').subtract(30, 'days'),
                  moment(),
                ],
                '45天': [
                  moment().startOf('day').subtract(45, 'days'),
                  moment(),
                ],
              }}
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [
                  moment('00:00:00', 'HH:mm:ss'),
                  moment('11:59:59', 'HH:mm:ss'),
                ],
              }}
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>

          <Form.Item label="  " style={{ marginLeft: '10px' }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Input.Group>
        <Form.Item>
          <ProTable
            rowKey="msgId"
            key={'msgId'}
            dataSource={dataSource}
            search={false}
            pagination={{ pageSize: 20 }}
            toolBarRender={false}
            loading={loading}
            scroll={{ x: 1200 }}
            // @ts-ignore
            columns={[
              {
                title: '消息ID',
                align: 'center',
                width: 280,
                dataIndex: 'msgId',
                key: 'messageId',
                render: (text, record) => (
                  <div
                    style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}
                    onDoubleClick={() => {
                      // @ts-ignore
                      onCopy(text, '消息ID')
                    }}
                  >
                    {text}
                  </div>
                ),
              },
              {
                title: '发送主机',
                align: 'center',
                dataIndex: 'bornHost',
                width: 100,
                key: 'bornHost',
              },
              {
                title: 'commitLog偏移量',
                align: 'center',
                dataIndex: 'commitLogOffset',
                width: 150,
                hideInTable: true,
                key: 'commitLogOffset',
              },
              {
                title: '生成时间',
                align: 'center',
                dataIndex: 'bornTimestamp',
                width: 150,
                key: 'bornTimestamp',
                render: (dom: any, record: { bornTimestamp: number }) => (
                  <div>{FormatDateTime(record.bornTimestamp / 1000)}</div>
                ),
              },
              {
                title: '消息属性',
                align: 'left',
                width: '0%',
                hideInTable: true,
                dataIndex: 'strProp',
                key: 'properties',
                render: (text, record) => {
                  // @ts-ignore
                  return (
                    <div
                      style={{
                        wordWrap: 'break-word',
                        wordBreak: 'break-word',
                      }}
                    >
                      <ReactJson
                        iconStyle="triangle"
                        collapsed={true}
                        theme="summerfruit:inverted"
                        displayDataTypes={false}
                        displayObjectSize={false}
                        // @ts-ignore
                        src={JSON.parse(record.strProp)}
                      />
                    </div>
                  )
                },
              },
              {
                title: '消息内容',
                align: 'left',
                dataIndex: 'messageBody',
                key: 'messageBody',
                width: '40%',
                render: (text, record) => {
                  // @ts-ignore
                  if (!record.messageBody || record.messageBody == '') {
                    return (
                      <div style={{ cursor: 'pointer', marginLeft: '20px' }}>
                        <Tag
                          color="green"
                          onClick={() => {
                            // @ts-ignore
                            getMessage(record.msgId, record)
                          }}
                        >
                          获取消息
                        </Tag>
                      </div>
                    )
                  } else {
                    // @ts-ignore
                    return (
                      <div
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                      >
                        <span
                          onDoubleClick={() => {
                            onCopy(
                              // @ts-ignore
                              JSON.stringify(record.messageBody),
                              '消息内容'
                            )
                          }}
                        >
                          <ReactJson
                            iconStyle="triangle"
                            collapsed={true}
                            theme="summerfruit:inverted"
                            displayDataTypes={false}
                            displayObjectSize={false}
                            // @ts-ignore
                            src={record.messageBody}
                          />
                        </span>
                      </div>
                    )
                  }
                },
              },
              {
                title: '操作',
                align: 'left',
                width: 120,
                dataIndex: 'detail',
                key: 'detail',
                render: (dom, record) => {
                  return [
                    <MessageDetail key={'messageDetail'} record={record} />,
                  ]
                },
              },
            ]}
          />
        </Form.Item>
      </Form>
    </PageContainer>
  )
}
export default Message
